package com.gupaoedu.vip.mall.file.controller;

import com.gupaoedu.mall.util.RespResult;
import com.gupaoedu.vip.mall.file.ceph.FileHandler;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Ceph文件上传下载控制器
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileHandler fileHandler;

    @Value("${cephurl}")
    private String cephurl;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public RespResult upload(MultipartFile file) throws IOException {
        fileHandler.upload(file.getOriginalFilename(), file.getBytes());
        return RespResult.ok(cephurl+file.getOriginalFilename());
    }

    /**
     * 文件下载
     * @param filename
     * @param response
     * @throws IOException
     */
    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) throws IOException {
        byte[] bytes = fileHandler.download(filename);
        ServletOutputStream os = response.getOutputStream(); //输出流输出文件
        os.write(bytes);
        os.flush();
        os.close();
    }
}
